<?php
namespace Home\Controller;
use Think\Controller;
class ProductController extends Controller{
	public function _initialize(){
		if($_COOKIE["manager_id"] == null){
			$index = new IndexController();
			$index->login();exit;
		}
	}
	
	public function index(){
		
		$this->display();
	}

	public function getProduct(){
		$plist=$this->getPlist();
		$arr=array('total'=>$plist[0],'rows'=>$plist[1]);
		echo json_encode($arr);
	}
	// 获取列表
	protected function getPlist(){
		$MP=M('product');
		$wh=$this->getWHere();
		$total=$MP->count();
		$st=I('get.offset');
		$limit=I('get.limit',12);
		$sort=I('get.sort','prodName');
		$order=I('get.order','desc');
		$catList=F('SYS/catList');
		$rda=$MP->field("prodId,prodName,price,catId")->where($wh)->limit($st,$limit)->order($sort." ".$order)->select();
		foreach($rda as $k=>$v){
			$v['catName']=$catList[$v['catId']]['catName'];
			$rda[$k]=$v;
		}
		return array($total,$rda);
	}
	//搜索条件
	protected function getWHere(){
		$search=I('get.search');
		$wh=array("prodId"=>array('neq',''));
		if($_GET['search']!=''){
			$wh['prodName']=array('like','%'.$search.'%');
		}
		return $wh;
	}
	//导入家具
	public function importD(){
	
		if(IS_POST){

			$filename=$_FILES["uploadfile"];
			
			if(!empty($filename)){
				// 导入数据，并更新其他数据，同时产生记录和更新产商卡的总数
				if($this->detectUploadFileMIME($filename)){
					set_time_limit(0);
					$resultData=$this->getExcelData($filename['tmp_name']);
					$error=$this->importCard($resultData,$uid);
					set_time_limit(30);
				}else{
					$error=array('status'=>0,'info'=>'文件格式不对,必须是 .xls 格式的文件');
					
				}
			}else{
				$error=array('status'=>0,'info'=>'文件为空');
			}
			exit(json_encode($error));
		}else{
			
			$this->display();
		}
	}
	// 导入店长
	protected function importCard($resultData,$uid){
		
		if(!empty($resultData['rows'])){
			$MS=M('product');
		
			$realAddCount=0;
			$updateOld=0;
			$restDataCC=0;
			$userGroup=array();
			$tt=time();
			foreach($resultData['rows'] as $k2=>$v2){
				if(empty($v2['prodId'])){continue;}
				$wh=array('prodId'=>$v2['prodId']);
				$memberinfo=$MS->where($wh)->find();
				
				if(empty($memberinfo)){
					$rid=$MS->add($v2);
					$realAddCount++;
				}else{
					if(empty($memberinfo['prodName'])){
						$sda1=array('prodName'=>$memberinfo['prodName']);
						$MS->where($wh)->setField($sda1);
						$updateOld++;
					}else{
						$restDataCC++;
					}
					
				}
			}
			
			$rcc=count($resultData['rows']);
			
			$msgg='导入成功，文件一共'.$rcc.'条记录。<br>'.'其中新增'.$realAddCount.'条<br>'.'原有记录'.$restDataCC.'条<br>再次更新'.$updateOld.'条 ！';
			if($rcc==$realAddCount){
				$msgg='成功导入家具';
			}
			$error=array('status'=>1,'info'=>$msgg);
		}else{
			$error=array('status'=>0,'info'=>'读取文件失败！请检查文件里面数据格式');
			
		}
		return $error;
	
		
	}
	// 获取导入数据的EXCEl 格式
	protected function getExcelData($filename){
		if(empty($filename)){return false;}
		
		import("Org.Util.Excel.Spreadsheet_Excel_Reader");
		$data = new \Spreadsheet_Excel_Reader();
		$data->setOutputEncoding('CP936');
		$data->read($filename);
		
		$newData=array();
		$newTitleArr=array();
		
		$columns=array('prodId','prodName','price','catId','catName');
		for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
			$temp = array();
			for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
				$temp[] = trim($data->sheets[0]['cells'][$i][$j]);
			}
			foreach($columns as $k=>$v){
				$vtemp=iconv("GBK","UTF-8",$temp[$k]);
				$row[$v]=$vtemp;
			}
			
			$this->checkCatList($row['catId'],$row['catName']);
			$newTitleArr[]=$row['prodId'];
			$newData[]=$row;
		}
		
		return array('rows'=>$newData,'indextitle'=>$newTitleArr);
	}
	//添加分类
	protected function checkCatList($catId,$catName){
		if(empty($catId) || empty($catName)) return false;
		$catList=F('SYS/catList');
		if(empty($catList)){
			F('SYS/catList',array($catId=>array('catId'=>$catId,'catName'=>$catName)));
		}else{
			$currCat=$catList[$catId];
			if(empty($currCat)){
				$catList[$catId]=array('catId'=>$catId,'catName'=>$catName);
				F('SYS/catList',$catList);
			}
		}
		$catList=F('SYS/catList');
		return $catList;
	}
	/** 
	 * Detect upload file type 
	 *  
	 * @param array $file            
	 * @return bool $flag 
	 */  
	public function detectUploadFileMIME($file) {  
	    // 1.through the file extension judgement 03 or 07  
	    $flag = 0; 
	    $file_array = explode ( ".", $file ["name"] );  
	    $file_extension = strtolower ( array_pop ( $file_array ) );  
	    
	    // 2.through the binary content to detect the file  
	    switch ($file_extension) {  
	        case "xls" :  
	            // 2003 excel  
	            $fh = fopen ( $file ["tmp_name"], "rb" );  
	            $bin = fread ( $fh, 8 );  
	            fclose ( $fh );  
	            $strinfo = @unpack ( "C8chars", $bin );  
	            $typecode = "";  
	            foreach ( $strinfo as $num ) {  
	                $typecode .= dechex ( $num );  
	            }  
	            if ($typecode == "d0cf11e0a1b11ae1") {  
	                $flag = 1;  
	            }  
	            break;  
	        case "xlsx" :  
	            // 2007 excel  
	            $fh = fopen ( $file ["tmp_name"], "rb" );  
	            $bin = fread ( $fh, 4 );  
	            fclose ( $fh );  
	            $strinfo = @unpack ( "C4chars", $bin );  
	            $typecode = "";  
	            foreach ( $strinfo as $num ) {  
	                $typecode .= dechex ( $num );  
	            }  
	            echo $typecode;  
	            if ($typecode == "504b34") {  
	                $flag = 1;  
	            }  
	            break;  
	    }  
	      
	    // 3.return the flag  
	    return $flag;  
	}
}